<template>
  <div class="wrap">
    <input type="file" accept=".docx" @change="handleFileUpload" />
    <br />
    <button @click="exportToWord">导出为 Word</button>
    <br />
    <div class="mainContent">
      <div class="toc-sidebar">
        <!-- <div
          v-for="item in tocItems"
          :key="item.id"
          :style="{ paddingLeft: (item.level - 2) * 20 + 'px' }"
          class="toc-item"
          @click="scrollToHeading(item.id)"
        >
          {{ item.text }}
        </div> -->
      </div>
      <editor-content :editor="editor" class="content" />
    </div>
  </div>
</template>
<script>
import { Editor, EditorContent } from "@tiptap/vue-2";
import StarterKit from "@tiptap/starter-kit";
import { Node } from "@tiptap/core";
import { exportAsDocx } from './js/exportToWord.js';

export default {
  components: {
    EditorContent,
  },
  data() {
    return {
      editor: null,
    };
  },
  mounted() {
    const CustomDiv = Node.create({
      name: "customDiv",
      group: "block",
      content: "inline*",
      attributes: "12ca",
      parseHTML() {
        return [{ tag: "div" }, { tag: "span" }];
      },
      renderHTML({ HTMLAttributes }) {
        console.log("HTMLAttributes===", HTMLAttributes);
        return ["div", HTMLAttributes, 0];
      },
    });

    this.editor = new Editor({
      extensions: [StarterKit, CustomDiv],
      content: `<div class='customDiv' >Start typing...</div><p>我是P</p><span>我是sPan</span>`,
      onUpdate: () => {
        // 内容变化时触发
        this.$emit("update", this.editor.getHTML());
      },
    });
  },
  methods: {
    handleFileUpload() {
      console.log("上传===");
      this.editor.commands.setContent({
        type: "doc",
        content: [
          {
            type: "customDiv", // 与自定义节点名称一致
            content: [{ type: "text", text: "Hello" }],
            attrs: { class: "my-div" },
          },
        ],
      });
    },
    insertDiv() {
      this.editor.commands.insertContent({
        type: "customDiv",
        content: [{ type: "text", text: "自定义 DIV" }],
        attrs: { class: "highlight" },
      });
    },
    exportToWord() {
      // 获取 Tiptap 的 HTML 内容
      const html = this.editor.getHTML();
      // 调用导出函数
      exportAsDocx(html, "tiptap-content.docx");
    },
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy();
    }
  },
};
</script>
<style lang="scss" scoped>
.mainContent {
  display: flex;
  .toc-sidebar {
    width: 20%;
    .toc-item {
      white-space: nowrap;
      text-align: left;
      text-overflow: ellipsis;
      overflow: hidden;
      cursor: pointer;
      margin: 4px 0;
    }
  }
  .editorElement {
    flex: 1;
  }
}
</style>